package com.myFwk.config.feign;

import com.myFwk.constant.Constants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Title:
 * @Description:
 * @Author: guowl
 * @version： 1.0
 * @Date:2021/9/2
 * @Copyright: Copyright(c)2021 RedaFlight.com All Rights Reserved
 * 异常 Feign调用出现权限问题 feign.FeignException$Unauthorized: [401] during [GET] to[....]
 * 解决办法为使用Feign的时候把请求的认证信息传递过去，或者资源服务那边开放一些接口。
 * 不过开放接口的话情况有点多，所以就选择把token携带过去了。feign提供了一个名为RequestInterceptor得拦截器，可以在请求的时候指定请求头
 */
@Configuration
public class FeignConfig implements RequestInterceptor {

    @Value("${basic.token:Basic ZndrLWFwaTpmd2stc2VjcmV0}")
    private String basicToken;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = attributes.getRequest().getHeader(HttpHeaders.AUTHORIZATION);
        if (token!=null) {
            //实现服务之间Token传递
            requestTemplate.header(HttpHeaders.AUTHORIZATION);
            requestTemplate.header(HttpHeaders.AUTHORIZATION, token);
        } else {
            requestTemplate.header("Authorization", basicToken);
        }
    }

    public static void main(String[] args) {
         String test=null;
         if(test!=null){
             System.out.println("testste");
         }

    }

}
